// pages/homePage/sleep/sleep.js
const app = getApp();
import F2 from '@antv/wx-f2';
let chart = null;
F2.Global.setTheme({
  colors: ["l(0) 0:#91D5FF 1:#40A9FF", "l(0) 0:#D3ADF7 1:#B37FEB"],
  appendPadding: [5, 15, 5, 15]
});
const {
  total_standards_child,
  total_standards_young,
  total_standards_adult,
  start_standards_child,
  start_standards_young,
  start_standards_adult,
  wake_standards,
  deep_standards_child,
  deep_standards_young,
  deep_standards_adult
} = require("../../../utils/standards-score.js");

function initChart(canvas, width, height) { // 使用 F2 绘制图表
  const data = [{
      name: "深睡",
      y: 0,
      x: "周一"
    },
    {
      name: "浅睡",
      y: 0,
      x: "周一"
    }
  ]
  chart = new F2.Chart({
    el: canvas,
    width: width,
    height: height
  });

  chart.source(data, {
    y: {
      ticks: [0, 3, 6, 9, 12]
    }
  });
  chart.tooltip({
    custom: true, // 自定义 tooltip 内容框
    onChange(obj) {
      const legend = chart.get('legendController').legends.top[0];
      const tooltipItems = obj.items;
      const legendItems = legend.items;
      const map = {};
      legendItems.map(item => {
        map[item.name] = Object.assign({}, item);
      });
      tooltipItems.map(item => {
        const {
          name,
          value
        } = item;
        if (map[name]) {
          map[name].value = (value) + "h";
        }
      });

      legend.valueStyle.fill = "#707070";
      legend.valueStyle.fontSize = 10;
      legend.titleStyle.fill = "#707070";
      legend.titleStyle.fontSize = 10;
      legend.setItems(Object.values(map));
    },
    onHide() {
      const legend = chart.get('legendController').legends.top[0];
      legend.setItems(chart.getLegendItems().country);
    }
  });
  let barWidth = 30 * (wx.getSystemInfoSync().windowWidth / 375) / 2;

  // chart.interval().position('x*y').color('l(0) 0:#91D5FF 1:#40A9FF').adjust('stack').size(barWidth);
  chart.interval().position('x*y').color('name').adjust('stack').size(barWidth);
  chart.render();
  return chart;
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    deviceNum: "",
    weekDay: '',
    end: "",
    now: "",
    age: "",
    nowWeek: "",
    weekText: "",
    nowMonth: "",
    monthText: "",
    nowYear: "",
    yearText: "",
    curTab: "1",
    sleepScore: 0,
    totalDay: "",
    beginatDay: "",
    wakeCountDay: "0",
    depthRateDay: "0",
    totalWeek: "",
    beginatWeek: "",
    wakeCountWeek: "0",
    depthRateWeek: "0",
    totalMonth: "",
    beginatMonth: "",
    wakeCountMonth: "0",
    depthRateMonth: "0",
    totalYear: "",
    beginatYear: "",
    wakeCountYear: "0",
    depthRateYear: "0",
    opts_week: {
      onInit: initChart
    },
    opts_month: {
      onInit: initChart
    },
    opts_year: {
      onInit: initChart
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let now = new Date(new Date().getTime() - 24 * 60 * 60 * 1000).format("yyyy/MM/dd");
    let nowMonth = new Date().format("yyyy/MM");
    let weekday = app.utils.formatWeekday(new Date(now).getDay());
    let startWDate = new Date(now).getTime() - 6 * 24 * 60 * 60 * 1000;
    startWDate = new Date(startWDate).format("yyyy/MM/dd");
    let weekText = startWDate + " - " + now;
    let startMDate = new Date(now).getTime() - 14 * 24 * 60 * 60 * 1000;
    startMDate = new Date(startMDate).format("yyyy/MM/dd");
    let monthText = startMDate + " - " + now;
    let startYDate = new Date(now).getTime() - 335 * 24 * 60 * 60 * 1000;
    startYDate = new Date(startYDate).format("yyyy/MM");
    let yearText = startYDate + " - " + nowMonth;

    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2]; //上一个页面

    this.setData({
      weekDay: weekday,
      now: now,
      age: prevPage.data.age,
      nowWeek: now,
      weekText: now,
      nowMonth: now,
      nowYear: now,
      end: now,
      weekText: weekText,
      monthText: monthText,
      yearText: yearText,
      deviceNum: wx.getStorageSync("deviceNum")
    })

    this.getSleepData(this.data.deviceNum, this.data.now, 1);

  },
  circleCanves(option) {
    var cxt_arc = wx.createCanvasContext(option.id);
    var gr = cxt_arc.createLinearGradient(0, 100, 100);
    gr.addColorStop(0, option.colorStart);
    gr.addColorStop(1, option.colorEnd);
    cxt_arc.setLineWidth(option.ringWidth);
    cxt_arc.setStrokeStyle(option.colorBg || '#d2d2d2');
    cxt_arc.setLineCap('round')
    cxt_arc.beginPath(); //开始一个新的路径
    cxt_arc.arc(option.x, option.y, option.radius, Math.PI * option.trackStart, Math.PI * option.trackEnd, false);
    //设置原点(80,80)，半径为50的圆的路径到当前路径
    cxt_arc.stroke(); //对当前路径进行描边

    cxt_arc.setLineWidth(option.ringWidth);
    cxt_arc.strokeStyle = gr;
    cxt_arc.setLineCap('round')
    cxt_arc.beginPath(); //开始一个新的路径
    cxt_arc.arc(option.x, option.y, option.radius, Math.PI * option.position1, Math.PI * option.position2, false);
    cxt_arc.stroke(); //对当前路径进行描边

    cxt_arc.draw();
  },
  drawCir(el, w, colorStart, colorEnd) {
    let width = wx.getSystemInfoSync().windowWidth;
    this.circleCanves({
      id: el,
      ringWidth: width / 375 * 5,
      radius: width / 375 * 25,
      position1: 1.5,
      position2: 2 * w + 1.5,
      x: width / 375 * 30,
      y: width / 375 * 30,
      colorStart: colorStart,
      colorEnd: colorEnd,
      trackStart: 2,
      trackEnd: 0
    });
  },
  bindDateChange(e) {

    let weekDay = app.utils.formatWeekday(new Date(e.detail.value).getDay())
    this.setData({
      now: e.detail.value.replace(/-/g, "/"),
      weekDay: weekDay
    })

    this.getSleepData(this.data.deviceNum, e.detail.value, 1);
  },
  bindDateChangeWeek(e) {
    let startDate = new Date(e.detail.value).getTime() - 6 * 24 * 60 * 60 * 1000;
    startDate = new Date(startDate).format("yyyy/MM/dd");
    let weekText = startDate + " - " + e.detail.value.replace(/-/g, "/");

    this.setData({
      nowWeek: e.detail.value,
      weekText: weekText
    })
    this.getSleepData(this.data.deviceNum, e.detail.value, 2);
  },
  bindDateChangeMonth(e) {
    let startDate = new Date(e.detail.value).getTime() - 14 * 24 * 60 * 60 * 1000;
    startDate = new Date(startDate).format("yyyy/MM/dd");
    let monthText = startDate + " - " + e.detail.value.replace(/-/g, "/");

    this.setData({
      nowMonth: e.detail.value,
      monthText: monthText
    })

    this.getSleepData(this.data.deviceNum, e.detail.value, 3);
  },
  bindDateChangeYear(e) {
    let startDate = new Date(e.detail.value).getTime() - 335 * 24 * 60 * 60 * 1000;
    startDate = new Date(startDate).format("yyyy/MM");
    let yearText = startDate + " - " + new Date(e.detail.value).format("yyyy/MM");

    this.setData({
      nowYear: e.detail.value,
      yearText: yearText
    })

    this.getSleepData(this.data.deviceNum, e.detail.value, 4);
  },
  // 点击tab切换
  swichNav: function(e) {
    if (this.data.curTab === e.currentTarget.dataset.current) return;
    this.setData({
      curTab: e.currentTarget.dataset.current
    })

    if (e.currentTarget.dataset.current == 2) {
      this.getSleepData(this.data.deviceNum, this.data.nowWeek, 2);
    } else if (e.currentTarget.dataset.current == 3) {
      this.getSleepData(this.data.deviceNum, this.data.nowMonth, 3);
    } else if (e.currentTarget.dataset.current == 4) {
      this.getSleepData(this.data.deviceNum, this.data.nowYear, 4);
    }
  },
  // 滑动切换tab
  bindChange: function(e) {
    this.setData({
      curTab: e.detail.current
    })
  },
  //计算睡眠得分
  getSleepScore(option) {
    let sleepLengthScore, sleepStartScore, wakeupScore, depthScore;
    let sleepTotal = option.sleepTotal / 3600;
    let sleepStart = new Date(option.sleepStartTime).getHours();
    let wakeUpCount = option.wakeUpCountl;
    let depthPercent = option.depthPercent;
    if (sleepTotal == 0 || !option.sleepTotal) return 0;

    let total_standards, start_standards, deep_standards, rate = [];
    if (this.data.age < 13 && this.data.age >= 6) {
      total_standards = total_standards_child;
      start_standards = start_standards_child;
      deep_standards = deep_standards_child;
      rate = [0.4, 0.2, 0.15, 0.25];
    } else if (this.data.age < 17 && this.data.age >= 14) {
      total_standards = total_standards_young;
      start_standards = start_standards_young;
      deep_standards = deep_standards_young;
      rate = [0.35, 0.25, 0.15, 0.25];
    } else {
      total_standards = total_standards_adult;
      start_standards = start_standards_adult;
      deep_standards = deep_standards_adult;
      rate = [0.35, 0.3, 0.15, 0.2];
    }

    total_standards.some(item => {
      if (item.begin <= sleepTotal && sleepTotal < item.end) {
        sleepLengthScore = item.score;
        return true;
      }
    })

    start_standards.some(item => {
      if (item.begin <= sleepStart && sleepStart < item.end) {
        sleepStartScore = item.score;
        return true;
      }
    })

    wake_standards.some(item => {
      if (item.begin <= wakeUpCount && wakeUpCount < item.end) {
        wakeupScore = item.score;
        return true;
      }
    })

    deep_standards.some(item => {
      if (item.begin <= depthPercent && depthPercent < item.end) {
        depthScore = item.score;
        return true;
      }
    })

    let score = sleepLengthScore * rate[0] + sleepStartScore * rate[1] + wakeupScore * rate[2] + depthScore * rate[3];
    return score;
  },
  //计算一个元素为数字的平均值
  getAvaDataofNum(list) {
    let avaData = 0,
      num = 0;
    list.forEach(item => {
      if (item != 0) {
        num++;
        avaData = avaData + item;
      }
    })

    return (avaData / num);
  },
  //计算平均数据
  getAvaData(list) {
    let num = 0,
      now = new Date("2019/02/18 00:00:00").getTime(),
      avaTotal = 0,
      avaStart = 0,
      avaPercent = 0,
      avaWakeCount = 0;
    list.forEach(item => {
      if (item.sleepTotal != 0) {
        num++;
        let clock_0 = new Date(new Date(item.sleepStartTime).format("yyyy/MM/dd 0:00:00")).getTime();
        let clock_12 = new Date(new Date(item.sleepStartTime).format("yyyy/MM/dd 12:00:00")).getTime();
        let rate_beginat;
        if (item.sleepStartTime > clock_12) {
          rate_beginat = (item.sleepStartTime - clock_0);
        } else {
          rate_beginat = (item.sleepStartTime - clock_0) + 24 * 3600 * 1000;
        }
        avaStart = avaStart + rate_beginat;
        avaTotal = avaTotal + item.sleepTotal;
        avaWakeCount = avaWakeCount + item.wakeUpCount;
        avaPercent = avaPercent + item.depthPercent;
      }

    })
    if (list.length == 1 || !num) num = 1;

    let timeDiff = avaStart / num;
    timeDiff = timeDiff > 24 * 3600 * 1000 ? (timeDiff - 24 * 3600 * 1000) : timeDiff;
    avaStart = new Date(timeDiff + now).format("hh:mm");
    avaTotal = avaTotal / num;
    avaWakeCount = avaWakeCount / num;
    avaPercent = avaPercent / num;
    return [avaTotal, avaStart, avaWakeCount, avaPercent, timeDiff];
  },
  sleepDayHandle(data) {
    if (!data || !data.length) data = [{
      sleepPeriodDate: new Date(this.data.now).getTime(),
      sleepTotal: 0,
      sleepStartTime: new Date(this.data.now).getTime(),
      wakeUpCount: 0,
      depthPercent: 0
    }];

    let sleep = data[0];
    let sleepScore = Math.round(this.getSleepScore(sleep));
    let rate_score = sleepScore / 100;

    let width = wx.getSystemInfoSync().windowWidth;
    let ringWidth = width / 375 * 10;
    let radius = width / 375 * 80;
    let x = ringWidth + radius;
    this.circleCanves({
      id: 'canvasArc',
      ringWidth: ringWidth,
      radius: radius,
      position1: 3 / 4,
      position2: 2 * rate_score + 0.75,
      x: x,
      y: x,
      colorStart: "#91D5FF",
      colorEnd: "#40A9FF",
      colorBg: "#b27eea",
      trackStart: 3 / 4,
      trackEnd: 1 / 4
    });

    let rate_total = sleep.sleepTotal / (12 * 3600);
    rate_total = rate_total >= 1 ? 1 : rate_total;
    let clock_0 = new Date(new Date(sleep.sleepStartTime).format("yyyy/MM/dd 0:00:00")).getTime();
    let clock_12 = new Date(new Date(sleep.sleepStartTime).format("yyyy/MM/dd 12:00:00")).getTime();
    let rate_beginat = (sleep.sleepStartTime - clock_12) / (12 * 3600 * 1000);
    if (sleep.sleepStartTime > clock_12) {
      rate_beginat = (sleep.sleepStartTime - clock_12) / (12 * 3600 * 1000);
    } else {
      rate_beginat = (sleep.sleepStartTime - clock_0) / (12 * 3600 * 1000);
    }
    rate_beginat = rate_beginat >= 1 ? 1 : rate_beginat;
    let rate_wakeCount = sleep.wakeUpCount / 8;
    rate_wakeCount = rate_wakeCount >= 1 ? 1 : rate_wakeCount;
    let rate_depth = sleep.depthPercent / 100;
    rate_depth = rate_depth >= 1 ? 1 : rate_depth;

    this.drawCir("can-total-day", rate_total, "#91D5FF", "#40A9FF");
    this.drawCir("can-beginat-day", rate_beginat, "#F9A39E", "#F77775");
    this.drawCir("can-wakecount-day", rate_wakeCount, "#FBD591", "#F8A941");
    this.drawCir("can-depthRate-day", rate_depth, "#D3ADF7", "#B37FEB");

    let hours = parseInt(sleep.sleepTotal / 3600);
    let minutes = parseInt((sleep.sleepTotal - hours * 3600) / 60);
    this.setData({
      sleepScore: sleepScore,
      totalDay: hours + "h" + minutes + "min",
      beginatDay: new Date(sleep.sleepStartTime).format("hh:mm"),
      wakeCountDay: sleep.wakeUpCount,
      depthRateDay: sleep.depthPercent,
    })
  },
  sleepWeekHandle(data) {
    if (!data || !data.length) data = [{
      sleepPeriodDate: new Date(this.data.nowWeek).getTime(),
      sleepTotal: 0,
      depthSleepTotal: 0,
      shallowSleepTotal: 0,
      sleepStartTime: new Date(this.data.nowWeek).getTime(),
      wakeUpCount: 0,
      depthPercent: 0
    }];
    let newArray = [],
      depthChartData = [],
      shallowChartData = [];

    for (let i = 0; i < data.length; i++) {
      let weekday = app.utils.formatWeekday(new Date(data[i].sleepPeriodDate).getDay()).replace("星期", "周");

      newArray.push({
        weekday: weekday,
        sleepPeriodDate: data[i].sleepPeriodDate,
        sleepTotal: data[i].sleepTotal,
        depthSleepTotal: data[i].depthSleepTotal,
        shallowSleepTotal: data[i].shallowSleepTotal,
        sleepStartTime: data[i].sleepStartTime,
        wakeUpCount: data[i].wakeUpCount,
        depthPercent: data[i].depthPercent
      })
    }

    this.dataRepair(newArray, this.data.nowWeek, 7).forEach(item => {
      depthChartData.push({
        name: "深睡",
        x: item.weekday,
        y: (item.depthSleepTotal / 3600).toFixed(1) * 1
      })
      shallowChartData.push({
        name: "浅睡",
        x: item.weekday,
        y: (item.shallowSleepTotal / 3600).toFixed(1) * 1
      })
    });

    let weekChartComponent = this.selectComponent('#column-week');
    weekChartComponent.chart.changeData(shallowChartData.concat(depthChartData));

    let avaData = this.getAvaData(newArray);
    let hours = parseInt(avaData[0] / 3600);
    let minutes = parseInt((avaData[0] - hours * 3600) / 60);
    this.setData({
      totalWeek: hours + "h" + minutes + "min",
      beginatWeek: avaData[1],
      wakeCountWeek: avaData[2].toFixed(1),
      depthRateWeek: parseInt(avaData[3])
    })

    let rate_total = avaData[0] / (12 * 3600);
    rate_total = rate_total >= 1 ? 1 : rate_total;
    let rate_beginat = avaData[4] / (12 * 3600 * 1000);
    rate_beginat = rate_beginat >= 1 ? 1 : rate_beginat;
    let rate_wakeCount = avaData[2] / 8;
    rate_wakeCount = rate_wakeCount >= 1 ? 1 : rate_wakeCount;
    let rate_depth = avaData[3] / 100;
    rate_depth = rate_depth >= 1 ? 1 : rate_depth;

    this.drawCir("can-total-week", rate_total, "#91D5FF", "#40A9FF");
    this.drawCir("can-beginat-week", rate_beginat, "#F9A39E", "#F77775");
    this.drawCir("can-wakecount-week", rate_wakeCount, "#FBD591", "#F8A941");
    this.drawCir("can-depthRate-week", rate_depth, "#D3ADF7", "#B37FEB");

  },
  sleepMonthHandle(data) {
    if (!data || !data.length) data = [{
      sleepPeriodDate: new Date(this.data.nowMonth).getTime(),
      sleepTotal: 0,
      depthSleepTotal: 0,
      shallowSleepTotal: 0,
      sleepStartTime: new Date(this.data.nowMonth).getTime(),
      wakeUpCount: 0,
      depthPercent: 0
    }];
    let newArray = [],
      depthChartData = [],
      shallowChartData = [];

    for (let i = 0; i < data.length; i++) {
      let weekday = app.utils.formatWeekday(new Date(data[i].sleepPeriodDate).getDay()).replace("星期", "周");

      newArray.push({
        weekday: weekday,
        sleepPeriodDate: data[i].sleepPeriodDate,
        sleepTotal: data[i].sleepTotal,
        depthSleepTotal: data[i].depthSleepTotal,
        shallowSleepTotal: data[i].shallowSleepTotal,
        sleepStartTime: data[i].sleepStartTime,
        wakeUpCount: data[i].wakeUpCount,
        depthPercent: data[i].depthPercent
      })
    }

    this.dataRepair(newArray, this.data.nowMonth, 15).forEach(item => {
      depthChartData.push({
        name: "深睡",
        x: item.date,
        y: (item.depthSleepTotal / 3600).toFixed(1) * 1
      })
      shallowChartData.push({
        name: "浅睡",
        x: item.date,
        y: (item.shallowSleepTotal / 3600).toFixed(1) * 1
      })
    });

    let monthChartComponent = this.selectComponent('#column-month');
    monthChartComponent.chart.changeData(shallowChartData.concat(depthChartData));

    let avaData = this.getAvaData(newArray);
    let hours = parseInt(avaData[0] / 3600);
    let minutes = parseInt((avaData[0] - hours * 3600) / 60);
    this.setData({
      totalMonth: hours + "h" + minutes + "min",
      beginatMonth: avaData[1],
      wakeCountMonth: avaData[2].toFixed(1),
      depthRateMonth: parseInt(avaData[3])
    })

    let rate_total = avaData[0] / (12 * 3600);
    rate_total = rate_total >= 1 ? 1 : rate_total;
    let rate_beginat = avaData[4] / (12 * 3600 * 1000);
    rate_beginat = rate_beginat >= 1 ? 1 : rate_beginat;
    let rate_wakeCount = avaData[2] / 8;
    rate_wakeCount = rate_wakeCount >= 1 ? 1 : rate_wakeCount;
    let rate_depth = avaData[3] / 100;
    rate_depth = rate_depth >= 1 ? 1 : rate_depth;

    this.drawCir("can-total-month", rate_total, "#91D5FF", "#40A9FF");
    this.drawCir("can-beginat-month", rate_beginat, "#F9A39E", "#F77775");
    this.drawCir("can-wakecount-month", rate_wakeCount, "#FBD591", "#F8A941");
    this.drawCir("can-depthRate-month", rate_depth, "#D3ADF7", "#B37FEB");

  },
  sleepYearHandle(data) {
    if (!data || !data.length) data = [{
      sleepPeriodDate: new Date(this.data.nowYear).getTime(),
      sleepTotal: 0,
      depthSleepTotal: 0,
      shallowSleepTotal: 0,
      sleepStartTime: new Date(this.data.nowYear).getTime(),
      wakeUpCount: 0,
      depthPercent: 0
    }];
    let newArray = [],
      depthChartData = [],
      shallowChartData = [];
    let dataYear = new Map([
      ["01", []],
      ["02", []],
      ["03", []],
      ["04", []],
      ["05", []],
      ["06", []],
      ["07", []],
      ["08", []],
      ["09", []],
      ["10", []],
      ["11", []],
      ["12", []]
    ])

    let dataYear1 = new Map([
      ["01", []],
      ["02", []],
      ["03", []],
      ["04", []],
      ["05", []],
      ["06", []],
      ["07", []],
      ["08", []],
      ["09", []],
      ["10", []],
      ["11", []],
      ["12", []]
    ])
    let startMonth;

    for (let i = 0; i < data.length; i++) {
      let weekday = new Date(data[i].sleepPeriodDate).format("MM");

      newArray.push({
        weekday: weekday,
        sleepPeriodDate: data[i].sleepPeriodDate,
        sleepTotal: data[i].sleepTotal,
        depthSleepTotal: data[i].depthSleepTotal,
        shallowSleepTotal: data[i].shallowSleepTotal,
        sleepStartTime: data[i].sleepStartTime,
        wakeUpCount: data[i].wakeUpCount,
        depthPercent: data[i].depthPercent
      })
    }

    this.dataRepair(newArray, this.data.nowYear, 365).forEach((item, index) => {
      if (index == 0) startMonth = item.month;
      let monthData = dataYear.get(item.month);
      monthData.push(item.shallowSleepTotal);
      dataYear.set(item.month, monthData);

      let monthData1 = dataYear1.get(item.month);
      monthData1.push(item.depthSleepTotal);
      dataYear1.set(item.month, monthData1);
    });

    dataYear.forEach((value, key) => {
      shallowChartData.push({
        name: "浅睡",
        y: (this.getAvaDataofNum(value) / 3600).toFixed(1) * 1 || 0,
        x: key
      })
    })

    dataYear1.forEach((value, key) => {
      depthChartData.push({
        name: "深睡",
        y: (this.getAvaDataofNum(value) / 3600).toFixed(1) * 1 || 0,
        x: key
      })
    })

    //按照开始月份调整数组顺序
    let index = startMonth * 1 - 1;
    let arrBegin = shallowChartData.slice(0, index);
    let arrEnd = shallowChartData.slice(index);
    let dataList = arrEnd.concat(arrBegin);
    let arrBegin1 = depthChartData.slice(0, index);
    let arrEnd1 = depthChartData.slice(index);
    let dataList1 = arrEnd1.concat(arrBegin1);

    let yearChartComponent = this.selectComponent('#column-year');
    yearChartComponent.chart.changeData(dataList.concat(dataList1));

    let avaData = this.getAvaData(newArray);
    let hours = parseInt(avaData[0] / 3600);
    let minutes = parseInt((avaData[0] - hours * 3600) / 60);
    this.setData({
      totalYear: hours + "h" + minutes + "min",
      beginatYear: avaData[1],
      wakeCountYear: avaData[2].toFixed(1),
      depthRateYear: parseInt(avaData[3])
    })

    let rate_total = avaData[0] / (12 * 3600);
    rate_total = rate_total >= 1 ? 1 : rate_total;
    let rate_beginat = avaData[4] / (12 * 3600 * 1000);
    rate_beginat = rate_beginat >= 1 ? 1 : rate_beginat;
    let rate_wakeCount = avaData[2] / 8;
    rate_wakeCount = rate_wakeCount >= 1 ? 1 : rate_wakeCount;
    let rate_depth = avaData[3] / 100;
    rate_depth = rate_depth >= 1 ? 1 : rate_depth;

    this.drawCir("can-total-year", rate_total, "#91D5FF", "#40A9FF");
    this.drawCir("can-beginat-year", rate_beginat, "#F9A39E", "#F77775");
    this.drawCir("can-wakecount-year", rate_wakeCount, "#FBD591", "#F8A941");
    this.drawCir("can-depthRate-year", rate_depth, "#D3ADF7", "#B37FEB");

  },
  //修复空白数据
  dataRepair(data, end, days) {
    let newArr = [];
    let endTime = new Date(end + " 23:59:59").getTime();
    let startTime = endTime - days * 24 * 3600 * 1000 + 1000;
    if (days == 365) {
      let year = new Date(endTime).getFullYear() - 1;
      let month = new Date(endTime).getMonth() + 2;
      month = month > 12 ? 12 : month;
      let date = year + "/" + month + "/01";
      startTime = new Date(date).getTime();
    }

    data.forEach((item, i) => {
      item.sleepPeriodDate = new Date(new Date(item.sleepPeriodDate).format("yyyy/MM/dd 18:00")).getTime();
    })

    data.forEach((item, i) => {
      if (i != 0) {
        let d = (item.sleepPeriodDate - data[i - 1].sleepPeriodDate) / (24 * 60 * 60 * 1000);
        d = Math.floor(d);
        if (d > 1) {
          for (let j = 0; j < d - 1; j++) {
            let time = new Date(data[i - 1].sleepPeriodDate + (j + 1) * (24 * 60 * 60 * 1000));
            let weekday = app.utils.formatWeekday(time.getDay()).replace("星期", "周");
            let month = time.format("MM");
            let date = time.format("dd");
            newArr.push({
              sleepTotal: 0,
              depthSleepTotal: 0,
              shallowSleepTotal: 0,
              wakeUpCount: 0,
              depthPercent: 0,
              weekday: weekday,
              month: month,
              date: date,
              sleepPeriodDate: time.getTime(),
              sleepStartTime: time.getTime()
            })
          }

          let month = new Date(item.sleepPeriodDate).format("MM");
          let date = new Date(item.sleepPeriodDate).format("dd");
          newArr.push({
            weekday: item.weekday,
            month: month,
            date: date,
            sleepPeriodDate: item.sleepPeriodDate,
            sleepTotal: item.sleepTotal,
            depthSleepTotal: item.depthSleepTotal,
            shallowSleepTotal: item.shallowSleepTotal,
            sleepStartTime: item.sleepStartTime,
            wakeUpCount: item.wakeUpCount,
            depthPercent: item.depthPercent
          })
        } else {
          let month = new Date(item.sleepPeriodDate).format("MM");
          let date = new Date(item.sleepPeriodDate).format("dd");
          newArr.push({
            weekday: item.weekday,
            month: month,
            date: date,
            sleepPeriodDate: item.sleepPeriodDate,
            sleepTotal: item.sleepTotal,
            depthSleepTotal: item.depthSleepTotal,
            shallowSleepTotal: item.shallowSleepTotal,
            sleepStartTime: item.sleepStartTime,
            wakeUpCount: item.wakeUpCount,
            depthPercent: item.depthPercent
          })
        }
      } else if (i == 0) {
        let d = (item.sleepPeriodDate - startTime) / (24 * 60 * 60 * 1000);
        d = Math.floor(d);
        if (d >= 1) {
          for (let j = 0; j < d; j++) {
            let time = new Date(startTime + j * (24 * 60 * 60 * 1000));
            let weekday = app.utils.formatWeekday(time.getDay()).replace("星期", "周");
            let month = time.format("MM");
            let date = time.format("dd");
            newArr.push({
              weekday: weekday,
              month: month,
              date: date,
              sleepTotal: 0,
              depthSleepTotal: 0,
              shallowSleepTotal: 0,
              wakeUpCount: 0,
              depthPercent: 0,
              sleepPeriodDate: time.getTime(),
              sleepStartTime: time.getTime()
            })
          }

          let month = new Date(item.sleepPeriodDate).format("MM");
          let date = new Date(item.sleepPeriodDate).format("dd");
          newArr.push({
            weekday: item.weekday,
            month: month,
            date: date,
            sleepPeriodDate: item.sleepPeriodDate,
            sleepTotal: item.sleepTotal,
            depthSleepTotal: item.depthSleepTotal,
            shallowSleepTotal: item.shallowSleepTotal,
            sleepStartTime: item.sleepStartTime,
            wakeUpCount: item.wakeUpCount,
            depthPercent: item.depthPercent
          })
        } else {
          let month = new Date(item.sleepPeriodDate).format("MM");
          let date = new Date(item.sleepPeriodDate).format("dd");
          newArr.push({
            weekday: item.weekday,
            month: month,
            date: date,
            sleepPeriodDate: item.sleepPeriodDate,
            sleepTotal: item.sleepTotal,
            depthSleepTotal: item.depthSleepTotal,
            shallowSleepTotal: item.shallowSleepTotal,
            sleepStartTime: item.sleepStartTime,
            wakeUpCount: item.wakeUpCount,
            depthPercent: item.depthPercent
          })
        }
      }
      //结尾不连续
      if (i == (data.length - 1)) {
        let d = (endTime - item.sleepPeriodDate) / (24 * 60 * 60 * 1000);
        d = Math.floor(d);
        if (d >= 1) {
          for (let j = 0; j < d; j++) {
            let time = new Date(item.sleepPeriodDate + (j + 1) * (24 * 60 * 60 * 1000));
            let weekday = app.utils.formatWeekday(time.getDay()).replace("星期", "周");
            let month = time.format("MM");
            let date = time.format("dd");
            newArr.push({
              weekday: weekday,
              month: month,
              date: date,
              sleepTotal: 0,
              depthSleepTotal: 0,
              shallowSleepTotal: 0,
              wakeUpCount: 0,
              depthPercent: 0,
              sleepStartTime: time.getTime(),
              sleepPeriodDate: time.getTime()
            })
          }
        }
      }

    })

    return newArr;
  },
  //根据手环设备号获取步数
  getSleepData(deviceNum, date, type) {
    let that = this;
    app.api.ajaxSubmit("/node/wx/home/getSleepData", {
      deviceNum: deviceNum,
      type: type,
      date: date
    }).then(response => {
      if (response.data.error == 10000) {
        if (type == 1) return that.sleepDayHandle(response.data.data);
        if (type == 2) return that.sleepWeekHandle(response.data.data);
        if (type == 3) return that.sleepMonthHandle(response.data.data);
        if (type == 4) return that.sleepYearHandle(response.data.data);
      }
    }).catch(err => {})
  }
})